package com.zzuli.practice.util;

import io.jsonwebtoken.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

public class JWTUtils {
    //常量
    //定义token返回头部key名称
    public static final String AUTH_HEADER_KEY = "access_eastos";
    //过期时间为10天
    public static final long EXPIRE =1000 * 60 * 60 * 24 * 10;

    /**
     * 根据用户名，创建jwtToken
     * @param username
     * @return
     */
    public static String createJwtToken(String username){
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //======header====
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                //======payload===
                .setSubject("user-login")
                .setId(UUID.randomUUID().toString())
                //过期时间
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE))
                //自定义数据
                .claim("username",username)
                .claim("islogin",true)
                //======singnature====
                .signWith(SignatureAlgorithm.HS256, Constant.SECRET)
                //=====拼接成字符串=====
                .compact();
        return jwtToken;
    }

    /**
     * 根据用户id和用户名，创建token
     * @param userid
     * @param username
     * @return
     */
    public static String createJwtToken(String userid,String username){
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //======header====
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                //======payload===
                .setSubject("user-login")
                .setId(UUID.randomUUID().toString())
                //过期时间
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE))
                //自定义数据
                .claim("userid",userid)
                .claim("username",username)
                .claim("islogin",true)
                //======singnature====
                .signWith(SignatureAlgorithm.HS256, Constant.SECRET)
                //=====拼接成字符串=====
                .compact();
        return jwtToken;
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static boolean checkToken(String token){
        if(token == null || token.isEmpty() || "".equals(token.trim())){
            return false;
        }
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(Constant.SECRET).parseClaimsJws(token);
        }catch (Exception ex){
            return false;
        }
        return true;
    }
    /**
     * 校验token
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request){
        String token = request.getHeader(AUTH_HEADER_KEY);
        if(token == null || token.isEmpty() || "".equals(token.trim())){
            return false;
        }
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(Constant.SECRET).parseClaimsJws(token);
        }catch (Exception ex){
            return false;
        }
        return true;
    }

    /**
     * 获得token数据
     * @param token
     * @return
     */
    public static Claims parseToken(String token){
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(Constant.SECRET).parseClaimsJws(token);
        //获得数据
        Claims claims = claimsJws.getBody();
        return claims;
    }
    /**
     * 获得token数据
     * @param token
     * @return
     */
    public static String getTokenUserName(String token){
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(Constant.SECRET).parseClaimsJws(token);
        //获得数据
        Claims claims = claimsJws.getBody();
        return claims.get("username").toString();
    }
    /**
     * 获得token数据
     * @param token
     * @return
     */
    public static String getTokenUserId(String token){
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(Constant.SECRET).parseClaimsJws(token);
        //获得数据
        Claims claims = claimsJws.getBody();
        return claims.get("userid").toString();
    }
    /**
     * 获得token数据
     * @param token
     * @return
     */
    public static String getTokenData(String token,String datakey){
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(Constant.SECRET).parseClaimsJws(token);
        //获得数据
        Claims claims = claimsJws.getBody();
        return claims.get(datakey).toString();
    }

    public static void main(String[] args) {
        //创建token
        String username = "admin";
        String jwtToken = createJwtToken(username);
        System.out.println(jwtToken);
        //检证token
        boolean result = checkToken(jwtToken);
        System.out.println(result);
        //获得数据
        System.out.println(getTokenUserName(jwtToken));
        System.out.println(getTokenData(jwtToken,"islogin"));
    }
}
